package com.dyzx.hbb.modules.fcxs.controller;

import cn.hutool.core.bean.BeanUtil;
import com.dyzx.hbb.common.base.Result;
import com.dyzx.hbb.common.config.MyLambdaQueryWrapper;
import com.dyzx.hbb.common.controller.BaseCustomController;
import com.dyzx.hbb.common.utils.DateFormat;
import com.dyzx.hbb.modules.fcxs.entity.FcxsHouse;
import com.dyzx.hbb.modules.fcxs.query.FcxsHouseQuery;
import com.dyzx.hbb.modules.fcxs.service.FcxsHouseService;
import com.dyzx.hbb.modules.fcxs.vo.FcxsHouseUVO;
import com.dyzx.hbb.modules.fcxs.vo.FcxsHouseVO;
import com.dyzx.hbb.modules.sys.entity.SysDictValue;
import com.dyzx.hbb.modules.sys.service.SysDictValueService;
import com.dyzx.hbb.security.context.SecurityContextHolder;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 房屋管理控制器
 * 
 * 功能说明：负责处理房屋信息的创建、查询、更新和删除等操作
 * 主要职责：
 * - 提供房屋信息的CRUD接口
 * - 支持按条件查询房屋列表
 * - 提供房屋简易列表查询接口（用于下拉选择）
 * - 自动生成房屋编号
 * - 计算房屋面积和总价
 * 
 * @author 开发团队
 * @version 1.0.0
 * @since 2023-05-30
 */
@Tag(name = "01.房屋管理", description = "房屋管理相关接口，包括房屋信息的创建、查询、更新和删除等操作")
@RestController
@RequestMapping("/fcxs/house")
public class FcxsHouseController extends BaseCustomController<
        FcxsHouseService,  // 服务接口
        FcxsHouse,         // 实体类
        FcxsHouseQuery    // 查询参数

        > {
    @Autowired
    private FcxsHouseService fcxsHouseService;
    @Autowired
    private SysDictValueService valueService;

    /**
     * 获取基础服务类
     * @return FcxsHouseService实例
     */
    @Override
    protected FcxsHouseService getBaseService() {
        return fcxsHouseService;
    }

    /**
     * 构建查询条件包装器
     * @param query 查询参数
     * @return 查询条件包装器
     */
    @Override
    protected MyLambdaQueryWrapper<FcxsHouse> queryWrapper(FcxsHouseQuery query) {
        MyLambdaQueryWrapper<FcxsHouse> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(FcxsHouse::getId)
                .select(FcxsHouse::getCategory)
                .select(FcxsHouse::getType)
                .select(FcxsHouse::getBuildingNum)
                .select(FcxsHouse::getFloor)
                .select(FcxsHouse::getRoomNum)
                .select(FcxsHouse::getHouseNo)
                .select(FcxsHouse::getInnerArea)
                .select(FcxsHouse::getPublicArea)
                .select(FcxsHouse::getArea)
                .select(FcxsHouse::getPrice)
                .select(FcxsHouse::getTotalPrice)
                .select(FcxsHouse::getStatus)
                .select(FcxsHouse::getCreateDate)
                .select(FcxsHouse::getUpdateDate)
                .select(FcxsHouse::getUnit)
                .organName(FcxsHouse::getOrganId).as("organ_name")
                .userName(FcxsHouse::getOperatorId).as("operator_name");
        if (query != null) {
            queryWrapper
                    .like(StringUtils.isNotBlank(query.getHouse_no()), FcxsHouse::getHouseNo, query.getHouse_no())
                    .findInSet(StringUtils.isNotBlank(query.getType()), FcxsHouse::getType, query.getType())
                    .findInSet(StringUtils.isNotBlank(query.getCategory()), FcxsHouse::getCategory, query.getCategory())
                    .eq(query.getPrice() != null, FcxsHouse::getPrice, query.getPrice())
                    .eq(query.getUnit() != null, FcxsHouse::getUnit, query.getUnit())
                    .eq(query.getBuilding_num() != null, FcxsHouse::getBuildingNum, query.getBuilding_num())
                    .eq(query.getFloor() != null, FcxsHouse::getFloor, query.getFloor())
                    .eq(query.getRoom_num() != null, FcxsHouse::getRoomNum, query.getRoom_num())
                    .dateBetween(StringUtils.isNotBlank(query.getCreate_date()), FcxsHouse::getCreateDate, DateFormat.DATE, query.getCreate_date())
                    .findInSet(StringUtils.isNotBlank(query.getStatus()), FcxsHouse::getStatus, query.getStatus());
        }
        return queryWrapper;
    }

    /**
     * 构建详情查询条件包装器
     * @return 详情查询条件包装器
     */
    @Override
    protected MyLambdaQueryWrapper<FcxsHouse> queryInfoWrapper() {
        MyLambdaQueryWrapper<FcxsHouse> queryWrapper = new MyLambdaQueryWrapper<>();
        queryWrapper.select(FcxsHouse::getId)
                .select(FcxsHouse::getCategory)
                .select(FcxsHouse::getType)
                .select(FcxsHouse::getBuildingNum)
                .select(FcxsHouse::getFloor)
                .select(FcxsHouse::getRoomNum)
                .select(FcxsHouse::getHouseNo)
                .select(FcxsHouse::getInnerArea)
                .select(FcxsHouse::getPublicArea)
                .select(FcxsHouse::getArea)
                .select(FcxsHouse::getPrice)
                .select(FcxsHouse::getTotalPrice)
                .select(FcxsHouse::getStatus)
                .select(FcxsHouse::getCreateDate)
                .select(FcxsHouse::getUpdateDate)
                .select(FcxsHouse::getUnit)
                .organName(FcxsHouse::getOrganId).as("organ_name")
                .userName(FcxsHouse::getOperatorId).as("operator_name");
        return queryWrapper;
    }
    // 可以添加特定于房屋管理的自定义方法


    /**
     * 获取房屋简易列表
     * @param category 房屋分类，可选
     * @return 房屋简易列表，包含ID和房屋编号
     */
    @Operation(summary = "获取房屋简易列表", description = "获取房屋的简易信息，仅包含ID和房屋编号，用于下拉选择")
    @GetMapping("/mini_list")
    public Result<List<Map<String, Object>>> miniList(
            @Parameter(description = "房屋分类，可选") @RequestParam(required = false, defaultValue = "") String category
    ) {
        MyLambdaQueryWrapper<FcxsHouse> wrapper = new MyLambdaQueryWrapper<>();

        wrapper.select(FcxsHouse::getId, FcxsHouse::getHouseNo);
        if (StringUtils.isNotBlank(category)) {

            wrapper.findInSet(StringUtils.isNotBlank(category), FcxsHouse::getCategory, category);
        }
        wrapper.orderByDesc(FcxsHouse::getUpdateDate);


        List<Map<String, Object>> list = getBaseService().listMaps(wrapper);
        return list.isEmpty() ? Result.error(404, "暂无数据") : Result.ok(list);
    }
//       FcxsHouseVO,       // 添加视图对象
//        FcxsHouseUVO       // 编辑视图对象

    //添加角色
    /**
     * 添加房屋信息
     * @param entity 房屋信息VO
     * @return 添加结果
     */
    @Operation(summary = "添加房屋信息", description = "创建新的房屋信息记录")
    @PostMapping
    public Result<Boolean> add(@Valid @Parameter(description = "房屋信息VO") @RequestBody FcxsHouseVO entity) {

        if (entity == null) {
            return Result.error("参数不能为空");
        }
        Long organId = SecurityContextHolder.getOrganId();
        Long opratorId = SecurityContextHolder.getUserId();
        FcxsHouse entityCopy = new FcxsHouse();
        BeanUtil.copyProperties(entity, entityCopy);
        System.out.println(entityCopy);
        entityCopy.setOperatorId(opratorId);
        entityCopy.setOrganId(organId);
        String houseNo = generateHouseNo(entityCopy);
        entityCopy.setHouseNo(houseNo);
        entityCopy.setArea(entityCopy.getInnerArea() + entityCopy.getPublicArea());
        System.out.println("保存前：" + entityCopy);
        System.out.println(entityCopy);
        entityCopy.setTotalPrice((entityCopy.getArea() * entityCopy.getPrice()) / 100);
        boolean save = getBaseService().save(entityCopy);

        return save ? Result.ok() : Result.error("保存失败");
    }

    /**
     * 生成房屋编号
     * @param entityCopy 房屋实体
     * @return 生成的房屋编号
     */
    private String generateHouseNo(FcxsHouse entityCopy) {
        Map<Integer, SysDictValue> byMapKey = valueService.findByMapKey("fcxs_house_type");
        if (byMapKey.isEmpty()) {
            throw new RuntimeException("字典表数据为空");
        }
        SysDictValue sysDictValue = byMapKey.get(entityCopy.getType());
        if (sysDictValue == null) {
            throw new RuntimeException("字典表数据不存在");
        }
        return (sysDictValue.getName() + "/" + entityCopy.getBuildingNum() + "-" + entityCopy.getUnit() + "-" + entityCopy.getFloor() + "-" + entityCopy.getRoomNum()).trim();
    }

    //删除角色
    /**
     * 删除房屋信息
     * @param id 房屋ID
     * @return 删除结果
     */
    @Operation(summary = "删除房屋信息", description = "根据ID删除房屋信息")
    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@Parameter(description = "房屋ID") @PathVariable Long id) {
        if (id == null) {
            return Result.error("id不能为空");
        }
        boolean result = getBaseService().removeById(id);
        return result ? Result.ok() : Result.error("删除失败");
    }

    //修改角色
    /**
     * 更新房屋信息
     * @param entity 房屋信息更新VO
     * @return 更新结果
     */
    @Operation(summary = "更新房屋信息", description = "修改已存在的房屋信息")
    @PutMapping
    public Result<Boolean> update(@Parameter(description = "房屋信息更新VO") @RequestBody FcxsHouseUVO entity) {
        if (entity == null) {
            return Result.error("参数不能为空");
        }
        FcxsHouse entityCopy = new FcxsHouse();
        BeanUtil.copyProperties(entity, entityCopy);
        //   entityCopy.setOrganId(organId);
        String houseNo = generateHouseNo(entityCopy);
        entityCopy.setHouseNo(houseNo);
        entityCopy.setArea(entityCopy.getInnerArea() + entityCopy.getPublicArea());
        System.out.println("保存前：" + entityCopy);
        System.out.println(entityCopy);
        //  entityCopy.setTotalPrice(entityCopy.getArea() * entityCopy.getPrice());
        entityCopy.setTotalPrice((entityCopy.getArea() * entityCopy.getPrice()) / 100);
        boolean update = getBaseService().updateById(entityCopy);

        return update ? Result.ok(true) : Result.error("保存失败");
    }
}
